package com.rookieCi.plugin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.rookieci.plugin.core.PluginActivity;
import com.rookieci.plugin.core.PluginManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn1).setOnClickListener(view -> Toast.makeText(MainActivity.this, "点什么点呀", Toast.LENGTH_SHORT).show());
        View btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(view -> openOther());
        btn2.postDelayed(() -> {
            PluginManager.getInstance()
                    //外部目录不让用.loadDex(getExternalFilesDir(null) + "/other-release-unsigned.apk"), 10);
                    .loadDex(getFilesDir() + "/other-release-unsigned.apk");
            otherLog();
        }, 10);
        PluginManager.init(getApplicationContext());
    }

    private void otherLog() {
        //可以做个加载成功的回调
        DexClassLoader dexClassLoader = PluginManager.getInstance().getDexClassLoader();
        if (dexClassLoader == null) return;
        try {
            Class<?> aClass = dexClassLoader.loadClass("com.rookieci.other.OtherLog");
            Object instance = aClass.newInstance();
            Method out = aClass.getMethod("out");
            out.invoke(instance);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void openOther() {
        //这里的login.apk,是我们把login插件打包生成后的apk文件，然后上传到手机的sd卡根目录
        PackageInfo packageInfo = PluginManager.getInstance().getPackageInfo();
        ActivityInfo[] activities = packageInfo.activities;
        if (activities == null || activities.length == 0) return;
        //其实这里的name是PluginActivity的全路径(包名+类名)
        String name = activities[0].name;
        Intent intent = new Intent(this, PluginActivity.class);
        intent.putExtra("className", name);
        startActivity(intent);
    }
}